<template>
  <div class="wrapper">
    <div class="top">
      <img
        src="@/assets/images/goBackImg.png"
        class="back"
        alt="header"
        @click="goBack"
      />
      <img
        src="@/assets/images/home.png"
        class="back home"
        alt="header"
        @click="goHome"
      />
    </div>
    <div class="main">
      <section class="avatar-box">
        <img src="@/assets/images/robot.png" alt="back" class="robot-icon" />
        <div class="title-desc">
          <span v-if="showText" v-typewriter="{ speed: 45, cursor: false }">{{
            currentAItext
          }}</span>
        </div>
      </section>
      <section class="content">
        <div class="nav-bar-box">
          <div class="nav-bar">
            <div class="steps-box">
              <div
                class="steps-item"
                v-for="(item, index) in steps"
                :key="index"
                :class="{
                  active: currentStep >= item.step,
                  activeBold: currentStep == item.step,
                }"
              >
                <div class="steps-item-title" @click="changeStep(item)">
                  步骤{{ index + 1 }}：{{ item.title }}
                </div>
                <img
                  v-if="index !== steps.length - 1"
                  src="@/assets/images/right-arrow-gray.png"
                  alt="arrow"
                  class="arrow-right"
                />
              </div>
            </div>
            <div class="switch-box">
              <van-switch
                v-model="isSmartRecommend"
                size="24"
                class="switch-btn"
                @change="changeIsSmartRecommend"
              />
              <span class="switch-text">是否允许AI顾问推荐其他志愿</span>
            </div>
            <div class="total-text">
              共有 <span class="total">{{ totalNum }}</span> 个志愿符合
            </div>
          </div>
        </div>
        <div class="component-box">
          <keep-alive>
            <component :is="currentComponent" @confirm="confirm" />
          </keep-alive>
        </div>
      </section>
    </div>
    <div class="bottom-btn" @click="nextStep">
      {{ currentStep == 3 ? '完 成' : '下一步' }}
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  shallowRef,
  computed,
  watchEffect,
  watch,
  defineAsyncComponent,
} from 'vue';
import { useRouter } from 'vue-router';
import { debounce } from 'lodash-es';
import { getRushSteadyGroupNum, getVolunteerCurInfo } from '@/api/volunteer';
import { useVolunteerStore } from '@/store/volunteer';

const FirstStep = defineAsyncComponent(() =>
  import('./components/FirstStep.vue')
);
const SecondStep = defineAsyncComponent(() =>
  import('./components/SecondStep.vue')
);
const ThirdStep = defineAsyncComponent(() =>
  import('./components/ThirdStep.vue')
);

const router = useRouter();

const store = useVolunteerStore();

const totalNum = ref(0);

const steps = [
  {
    step: 1,
    title: '意向院校',
    component: FirstStep,
  },
  {
    step: 2,
    title: '意向专业',
    component: SecondStep,
  },
  {
    step: 3,
    title: '选择策略',
    component: ThirdStep,
  },
];

const showText = ref(true);
let counter = 0;

const aiTexts = [
  '您对院校有什么要求都可以告诉我哦!',
  '你可以选择更多偏好，这样符合的志愿会更多噢~',
  '符合的志愿过少，请勾选允许我推荐其他志愿噢~',
];

const total = ref(0);

const currentAItext = ref(aiTexts[0]);

const isSmartRecommend = ref(false);
const defaultBatchType = computed(() => store.defaultBatchType);
const volunteerInfo = computed(() => store.volunteerInfo);
const firstStepData = computed(() => store.firstStepData);
const secondStepData = computed(() => store.secondStepData);

const volunteerNum = ref(0);

const getVolunteerCurInfoFn = async () => {
  const params = {
    batchType: defaultBatchType.value,
    rankNum: volunteerInfo.value.position,
    regionId: volunteerInfo.value.regionId,
    score: volunteerInfo.value.score,
    subject: volunteerInfo.value.relSubject,
  };
  const res = await getVolunteerCurInfo(params);
  if (res.code == 200) {
    volunteerNum.value = res.data.totalVolunteerNum;
  }
};
const changeIsSmartRecommend = (value) => {
  store.setIsSmartRecommend(value);
};

const getRushSteadyGroupNumFn = async () => {
  const params = {
    groupLevel: '1',
    subject: volunteerInfo.value.relSubject,
    searchAllowSubject: volunteerInfo.value.relSubject,
    subjectType: volunteerInfo.value.subjectType,
    recordYear: volunteerInfo.value.defaultYear,
    userScore: +volunteerInfo.value.score,
    rushSteadyState: '',
    userMinScore: +volunteerInfo.value.score - 70,
    userMaxScore: +volunteerInfo.value.score + 30,
    localRegionId: volunteerInfo.value.regionId,
    batchType: defaultBatchType.value,
    collegeSearch: {
      regionIdList: firstStepData.value.regionIdList,
      collegeType: firstStepData.value.collegeType,
      dualClassName: firstStepData.value.dualClassName,
      natureName: firstStepData.value.natureName,
      levelName: firstStepData.value.levelName,
    },
    professionSearch: {
      secondPositionTagNames: secondStepData.value,
    },
  };
  const res = await getRushSteadyGroupNum(params);
  if (res.code == 200) {
    counter++;
    let data10 = res.data[10] || 0;
    let data20 = res.data[20] || 0;
    let data30 = res.data[30] || 0;
    totalNum.value = data10 + data20 + data30;
  }
};

const setAIText = debounce((textIndex) => {
  currentAItext.value = aiTexts[textIndex];
  showText.value = true;
}, 500); // 300ms 可根据需要调整

watch(
  totalNum,
  (newVal) => {
    // 初次进去不改变文案
    if (counter < 2) {
      return;
    }
    // 当前totalNum数量大于volunteerNum数量，改变文案
    if (totalNum.value < volunteerNum.value && totalNum.value > 15) {
      showText.value = false;
      setAIText(1);
    } else if (totalNum.value < 15) {
      showText.value = false;
      setAIText(2);
    } else if (totalNum.value >= volunteerNum.value) {
      showText.value = false;
      setAIText(1);
    }
  },
  { deep: true }
);

getVolunteerCurInfoFn();

watchEffect(() => {
  getRushSteadyGroupNumFn();
});

const goBack = () => {
  resetData();
  router.back();
};

const goHome = () => {
  resetData();
  router.replace({
    path: '/home',
  });
};

const resetData = () => {
  store.setFirstStepData({});
  store.setSecondStepData('');
  store.setThirdStepData({});
};

const currentStep = ref(1);

let currentComponent = shallowRef(FirstStep);

const changeStep = (item) => {
  currentStep.value = item.step;
  currentComponent.value = item.component;
};

const nextStep = () => {
  if (currentStep.value == 3) {
    router.push('/createVolunteer');
    return;
  }
  currentStep.value++;
  currentComponent.value = steps[currentStep.value - 1].component;
};

const confirm = (type, data) => {
  console.log(type, data);
};

onMounted(() => {});
</script>

<style scoped lang="scss">
.wrapper {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background: url('@/assets/images/homeBg.png') no-repeat center center;
  background-size: 100% 100%;
  position: relative;
  .top {
    position: absolute;
    padding: 32px 32px 30px 32px;
    .back {
      width: 40px;
      height: 40px;
    }
    .home {
      margin-left: 24px;
    }
  }
  .main {
    padding: 42px 32px 0 32px;
    .avatar-box {
      display: flex;
      align-items: center;
      padding-left: 30%;
      margin-bottom: 12px;
      .title-desc {
        width: 530px;
        height: 70px;
        padding: 0 28px;
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 24px;
        color: #333333;
        background-color: #fff;
        border-radius: 8px;
      }
      .robot-icon {
        width: 94px;
        height: 80px;
      }
    }
    .content {
      box-sizing: border-box;
      background-color: #fff;
      border-radius: 32px 32px 0 0;
      .nav-bar-box {
        padding: 20px 28px 0 28px;
        .nav-bar {
          display: flex;
          justify-content: space-between;
          border-bottom: 1px solid #bdbdbd;
          padding-bottom: 16px;
          .steps-box {
            display: flex;
            align-items: center;
            .steps-item {
              display: flex;
              align-items: center;
              &.active {
                .steps-item-title {
                  color: $primary-color;
                  border: 1px solid $primary-color;
                }
              }
              &.activeBold {
                .steps-item-title {
                  font-weight: bold;
                  color: $primary-color;
                  border: 1px solid $primary-color;
                }
              }
              .steps-item-title {
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                padding: 8px 22px;
                font-size: 24px;
                color: #555;
                font-weight: 400;
              }
              .arrow-right {
                margin: 0 8px;
                width: 24px;
                height: 24px;
              }
            }
          }
          .switch-box {
            display: flex;
            align-items: center;
            .switch-btn {
              margin-right: 20px;
            }
            .switch-text {
              font-size: 22px;
              color: #555550;
            }
          }
          .total-text {
            font-size: 20px;
            margin-bottom: 20px;
            .total {
              font-size: 38px;
              padding: 0 4px;
              font-family: D-DIN-PRO-600-SemiBold;
              color: #ff5052;
            }
          }
        }
      }
      .component-box {
        height: calc(100vh - 230px);
        position: relative;
        overflow: hidden;
      }
    }
  }
  .bottom-btn {
    position: fixed;
    z-index: 100;
    bottom: 24px;
    left: 50%;
    transform: translateX(-50%);
    padding: 14px 0;
    text-align: center;
    width: 430px;
    background: $primary-color;
    border-radius: 12px;
    color: #fff;
    font-size: 24px;
    font-weight: bold;
  }
}
</style>
